import React, { Component } from 'react'
import './style.less'
import {Link} from 'react-router-dom'
import {  httpPost } from "../../../http"



export default class LoginForm extends Component{
   constructor() {
    super();
    this.state = {
      username:"",
      password:''
    };
    
  }
   usernameChange(event) {
    this.setState({
      username: event.target.value
    });
  }
  passwordChange(event) {
    this.setState({
      password: event.target.value
    });
  }
  handleSubmit(event){
    console.log(this.state.username,this.state.password)
    event.preventDefault();
      if(!this.state.username||!this.state.password){
           
           alert('内容不能为空');
      }
      if(this.state.username||this.state.password){ 
            httpPost("http://localhost:3001/login",{
              username:this.state.username,
              password:this.state.password
            })
            .then(res=>{
              return res.json();
            })
            .then(data=>{
              if(data.length >0){
                 alert("登录成功")
                  this.props.history.push('/home')
              }else{
                 alert("登录失败,用户名或密码错误")
                 this.setState({
                  username:"",
                  password:''
                 })
                 
              }
            })
          }
  }
   
     
  render(){
    
    return(
      <div className='login-form'>
        <form onSubmit={this.handleSubmit.bind(this)}>
          <ul className='form-input'>
            <li>
              <input type='text' placeholder='输入手机号' value={this.state.username} onChange={this.usernameChange.bind(this)} />
            </li>
            <li>
              <input type='password' placeholder='输入密码' value={this.state.password} onChange={this.passwordChange.bind(this)} />
            </li>
            <li>
              <input type='submit' className='submit' value='登录' />
            </li>
          </ul>
        </form>
        <div className='login-text clearfix'>
          <Link to='/login/register'><span className='fl'>新用户注册</span></Link>
          <Link to='/login/forget'><span className='fr'>忘记密码?</span></Link>
        </div>
      </div>
    )
  }
}
